package com.hadoop.service.impl;

import com.alibaba.fastjson.JSON;
import com.hadoop.domain.Apply;
import com.hadoop.service.IWorkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class WorkServiceImpl implements IWorkService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean saveApply(Apply apply) {
        String json = JSON.toJSONString(apply);
        Long apply1 = redisTemplate.opsForList().rightPush("username:"+apply.getUsername(), json);
        return apply1>0;
    }

    @Override
    public List<Apply> getApplyList(Integer username) {
        List<String> list = redisTemplate.opsForList().range("username:" + username, 0, -1);
        if (list!=null) {
            List<Apply> applyList = new ArrayList<>();
            for (String s : list) {
                Apply apply = JSON.parseObject(s, Apply.class);
                applyList.add(apply);
            }
            return applyList;
        } else {
            return null;
        }
    }

    @Override
    public boolean delApply(Integer username, String id) {
        List<Apply> applyList = getApplyList(username);
        int index=0;
        if (applyList!=null){
            for (Apply apply : applyList) {
                if (apply.getId().equals(id)){
                    index=applyList.indexOf(apply);
                }
            }
        }
        applyList.remove(index);
        redisTemplate.opsForList().getOperations().delete("username:"+username);
        for (Apply apply : applyList) {
            saveApply(apply);
        }
        return true;
    }
}
